package logic

import (
	"context"
	"errors"
	"hippo-fresh/model/mysql"

	"hippo-fresh/hippofreshrpc/hippofreshrpc"
	"hippo-fresh/hippofreshrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShopAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShopAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShopAddLogic {
	return &ShopAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 商品创建
func (l *ShopAddLogic) ShopAdd(in *hippofreshrpc.ShopAddRequest) (*hippofreshrpc.ShopAddResponse, error) {
	// todo: add your logic here and delete this line

	tx := mysql.DB.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	if err := tx.Error; err != nil {
		return nil, errors.New("事务开启失败")
	}

	var good mysql.Shop
	err := good.FindGoodByName(tx, in.Name)
	if err == nil {
		tx.Rollback()
		return nil, errors.New("该商品已存在")
	}

	var class mysql.Class
	err = class.FindClassByName(tx, in.ClassName)
	if err != nil {
		class = mysql.Class{
			Name: in.Name,
		}

		err := class.ClassAdd(tx)
		if err != nil {
			tx.Rollback()
			return nil, errors.New("分类添加失败")
		}
	}

	shop := mysql.Shop{
		Style:   in.Style,
		Name:    in.Name,
		Price:   float64(in.Price),
		ClassId: int64(class.ID),
	}
	err = shop.ShopAdd(tx)
	if err != nil {
		tx.Rollback()
		return nil, err
	}

	return &hippofreshrpc.ShopAddResponse{
		ShopId: int64(shop.ID),
	}, tx.Commit().Error
}
